package JUC;

import java.util.concurrent.atomic.LongAdder;

/**
 * @author 豆包LU
 * @date 2023/5/22 17:15
 */
public class LongAdderExample {
    public static void main(String[] args) {
        // 创建一个LongAdder对象
        LongAdder longAdder = new LongAdder();

        // 创建并启动多个线程对计数器进行累加操作
        Thread[] threads = new Thread[5];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 10000; j++) {
                    longAdder.increment();
                }
                // 获取当前的计数总和并重置计数器
                long sum = longAdder.sumThenReset();
                // 输出计数总和
                System.out.println("计数总和：" + sum);
            });
            threads[i].start();
        }

        // 等待所有线程执行完毕
        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }




    }
}
